package com.aitoedu.server.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.aitoedu.server.vo.CourseCreateVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aitoedu.server.entity.Course;
import com.aitoedu.server.service.CourseService;
import com.aitoedu.server.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
* @author 曹正豪
* @description 针对表【course(课程信息)】的数据库操作Service实现
* @createDate 2024-10-14 19:14:27
*/
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course>
    implements CourseService{

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> myCourse() {
        Long tid = Long.valueOf(StpUtil.getLoginId().toString());
        List<Course> courses = courseMapper.selectList(new QueryWrapper<Course>().eq("tid",tid));
        return courses;
    }

    @Override
    public CourseCreateVO createCourse(String courseName) {
        Long tid = Long.valueOf(StpUtil.getLoginId().toString());
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        int code;
        while(true){
            Random random = new Random();
            code = random.nextInt(900000) + 100000;
            Course course = courseMapper.selectOne(queryWrapper.eq("code", code));
            if(course == null) break;
        }
        Course course = Course.builder()
                .cname(courseName)
                .tid(tid)
                .code(code)
                .createTime(LocalDateTime.now())
                .build();
        courseMapper.add(course);
        return new CourseCreateVO(course.getId(), code);
    }
}




